<?php

namespace App\Http\Middleware;

use Closure;
use App\Service\WechatOauthShareService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Overtrue\Socialite\SocialiteManager;
use Overtrue\Socialite\User as SocialiteUser;

class ChangGengAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $scope = 'snsapi_base')
    {
        $sessionKey = 'wechat.oauth_user.default';

        if (env('WECHAT_DEBUG', false)) {
            $user = new SocialiteUser([
                'id' => 'oVsMZ6P2jX1uvFK-pNdS0nRA8K30',
                'name' => '测试',
                'nickname' => '测试',
                'avatar' => 'http://thirdwx.qlogo.cn/mmopen/vi_32/ucIOqQI5mIQmVQe6hriaKYOfDC7rGqS44hUewb5qCTwEJkmaKAN4vm4GlPEBrtBRVVLCsOo3fbVAKKoTb8J0zog/132',
                'email' => null,
                'original' => [],
                'provider' => 'WeChat',
            ]);
            session([$sessionKey => $user]);
            return $next($request);
        }

        if (!session($sessionKey, [])) {
            $config = config('wechat.official_account.default');
            $app    = Factory::officialAccount($config);
            if ($request->input('code')) {
                $userInfo = $app->oauth->user() ?? [];
                // session()->put('officialAccount_token', $userInfo['id']);
                // session()->save();
                session([$sessionKey => $userInfo]);
            } else {
                $config['scope'] = $scope;
                $socialiteManager   = new SocialiteManager($config);
                $socialiteManager->extend('wechat_share', function ($config) {
                    return new WechatOauthShareService($config);
                });
                return $socialiteManager->driver('wechat_share')->redirect()->send();
            }
        }

        return $next($request);
    }
}
